import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
import login from '@/views/login'
import layout from '@/layout'
import home from '@/views/home'
import ask from '@/views/ask'
import video from '@/views/video'
import mine from '@/views/mine'
import edit from '@/views/mine/edit'
import article from '@/views/home/article'
import search from '@/views/searchs'
import xiangqin from '@/views/searchs/xiangqin'
import chat from '@/views/chat'


const routes = [
  { path: '', redirect: '/layout/home' },
  {
    name: 'edit',
    path: '/mine/edit',
    component: edit
  },
  {
    name: 'chat',
    path: '/mine/chat',
    component: chat
  },
  {
    name: 'search',
    path: '/search',
    component: search
  },
  { name: 'xiangqin', path: '/search/xiangqin', component: xiangqin },
  {
    name: 'article',
    path: '/home/article',
    component: article
  },
  {
    name: 'login',
    path: '/login',
    component: login
  },
  {
    name: 'layout',
    path: '/layout',
    component: layout,
    children: [
      { name: 'home', path: 'home', component: home, meta: { needKeep: true } },
      { name: 'ask', path: 'ask', component: ask },
      { name: 'video', path: 'video', component: video },
      {
        name: 'mine', path: 'mine', component: mine,
        meta:
          { needLogin: true }
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
//导入store
import store from '@/store'
router.beforeEach((to, from, next) => {
  if (to.meta.needLogin) {
    if (store.state.tokenobj.token) {
      next()
    } else {
      //跳转前加入轻提示
      Vue.prototype.$toast.fail('请先登陆');
      next('/login?back=' + to.path)
    }
  } else {
    next()
  }
})
// vue-router3.1后新增了一些跳转的警告
// 如果不想出现这些警告，使用如下代码即可把报错吞掉
const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(error => error)
}

export default router
